<script lang="ts" setup>
	import { ref, Ref, onMounted, defineProps, computed, onBeforeMount } from 'vue'
	import { getQuestions, addAnswers } from '@/api/psychology/task.js'
	import { getReports } from '@/api/psychology/report.js'



	const props = defineProps({ tabIds: { type: [Array, String], default: [] }, taskId: { type: String, default: '' } })

	let currentProgress = computed(() => {
		return Math.ceil((finishedNum.value) / total.value * 100) ?? 0;
	});

	let taskObj = ref<object>({})

	let tabs = ref<any[]>([]);
	// 当前选中的标签索引
	let currentTabIndex = ref(0);
	const finishedNum = ref(0);
	// console.log(props.tabIds, props.taskId) 	
	// 所有的问题列表 
	let question = ref<any[]>([]);
	// 量表名称
	const scaleName = ref('')
	let ralTabIds : string[] = props.tabIds.split(",");
	try {
		ralTabIds = props.tabIds?.split(",") || [];
	} catch (error) {
		console.error("无效的tabIds格式");
	}
	onMounted(() => {
		getQuestions(ralTabIds, props.taskId).then((res : any) => {
			if (res.data.code == 200) {
				//整个任务对象
				taskObj = res.data.data
				//整个任务对象的题数
				total.value = taskObj.queCount

				//量表名称
				scaleName.value = taskObj?.tableQAndAVO[0].name
				//总题数减去未做题数，等于已做题数
				finishedNum.value = taskObj.queCount - taskObj.unfinished
				//如果已做题数大于0则表示已经做过但未做完
				if (finishedNum.value > 0) {
					//存储量表名称
					tabs.value = res.data.data.tableQAndAVO.map(item => item.name);
					//所有量表的题目数组
					question.value = res.data.data.tableQAndAVO.map(item => item.questionList);
					let shouldBreak = false;
					for (const [indexs, items] of res.data.data.tableQAndAVO.entries()) {

						for (const [index, item] of items.questionList.entries()) {
							if (item.optId == null) {
								questionItem.value = question.value[indexs][index];
								currentTabIndex.value = indexs;
								curr_index.value = index;
								const newAnswer : AnswerItem = {
									questionId: questionItem.value.id,
									selectId: item.id,
									tabId: questionItem.value.tabId,
								};
								paramVal.push(newAnswer);
								const newItem : CacheItem = {
									tabIndex: currentTabIndex.value,
									quIndex: curr_index.value,
									answers: paramVal
								};
								shouldBreak = true; // 设置标志变量为 true，表示要终止外层循环和内层循环
								break; // 终止内层循环
							}
						}
						if (shouldBreak) {
							break; // 如果标志变量为 true，终止外层循环
						}
					}
				} else {

					//存储的是量表名称
					tabs.value = res.data.data.tableQAndAVO.map(item => item.name);
					question.value = res.data.data.tableQAndAVO.map(item => item.questionList);
					questionItem.value = question.value[currentTabIndex.value][0];

				}

				questionListPop()
				if (Array.isArray(question.value[currentTabIndex.value])) {
				} else {
				}
			}
		}).catch(error => {
		})
	}
	)

	onBeforeMount(() => {
		window.addEventListener("beforeunload", function (e) {

			const pages = getCurrentPages();
			const pageInfo = pages.map(page => ({
				url: page.route,
				options: page.options, // 查询参数
				// 可以添加其他自定义状态或信息
			}));
			localStorage.setItem('pageStack', JSON.stringify(pageInfo));
		});
	})

	const handlePopstate = ((event) => {
	})
	const total = ref(0);
	let curr_index = ref(0)
	let questionItem = ref<any>()
	const isOut = ref(false)
	let isOpenQuestListPop = ref(false)
	let paramVal : AnswerItem[] = []

	interface CacheItem {
		tabIndex : number;
		quIndex : number;
		answers : AnswerItem[];
		curr_index : number;

	}

	interface AnswerItem {
		questionId : string;
		selectId : string;
		tabId : string;
		curr_index : number;
	}
	let cacheRegion : CacheItem[] = [];

	interface allQuestionList {

	}

	// 节流函数
	function throttle(func, delay) {
		let previous = 0;
		return function (...args) {
			const now = Date.now();
			if (now - previous >= delay) {
				func.apply(this, args);
				previous = now;
			}
		};
	}



	// 题目改变 
	/*
	questionid 问题的id
	selectId 选择的选项的id
	tabId 当前表的id
	
	*/
	const handleOptionClick = (questionId : string, selectId : string, tabId : string, item : object) => {
		if (item.optId == null) {
			finishedNum.value = finishedNum.value + 1;
		}
		item.optId = selectId;
		// 创建的回答题目对象
		const newAnswer : AnswerItem = {
			questionId,
			selectId,
			tabId,
			curr_index,
		};
		paramVal.push(newAnswer);
		addAnswers(newAnswer.selectId, newAnswer.questionId, newAnswer.tabId, props.taskId).then((res : any) => {

			if (res.data.success) {
				if (curr_index.value < question.value[currentTabIndex.value].length - 1) {
					curr_index.value++;
					// 缓冲数据的存储 
					const cacheItemIndex = cacheRegion.findIndex(item => { item.tabIndex === currentTabIndex.value; });
					if (cacheItemIndex !== -1) {
						// 如果找到对应的缓存项，则更新 answers 数组
						cacheRegion[currentTabIndex.value].answers = paramVal;
						cacheRegion[currentTabIndex.value].quIndex += 1;
					} else {
						// 如果没有找到对应的缓存项，则创建新的缓存项并添加到 cacheRegion 数组中
						const newItem : CacheItem = {
							tabIndex: currentTabIndex.value,
							quIndex: curr_index.value,
							answers: paramVal,
							curr_index: curr_index.value
						};

						cacheRegion.push(newItem);
					}
					questionItem.value = question.value[currentTabIndex.value][curr_index.value]
				} else {
					if (currentTabIndex.value < question.value.length - 1) {
						onChange(currentTabIndex.value++)
						curr_index.value = 0;
						questionItem.value = question.value[currentTabIndex.value][curr_index.value]
					} else {

					}


				}
			} else {
				// finishedNum.value = finishedNum.value - 1  //删除了回滚
				item.optId = ""
			}
		})



	}

	const throttledHandleOptionClick = throttle(handleOptionClick, 500); // 1000毫秒的延迟


	const onChange = (index : number) => {
		const cacheItemIndex = cacheRegion.findIndex(item => item.tabIndex === index);
		if (cacheItemIndex !== -1) {
			curr_index.value = cacheRegion[index].quIndex;
			paramVal = cacheRegion[index].answers;
		} else {
			// 如果没有找到对应的缓存项，则创建新的缓存项并添加到 cacheRegion 数组中
			curr_index.value = 0;
			const newItem : CacheItem = {
				tabIndex: currentTabIndex.value,
				quIndex: curr_index.value,
				answers: []
			};
			paramVal = [];
			cacheRegion.push(newItem);
		}
		questionItem.value = question.value[currentTabIndex.value][curr_index.value]
	}

	const back = () => {
		if (curr_index.value > 0) {
			curr_index.value--;
			questionItem.value = question.value[currentTabIndex.value][curr_index.value]
			if (cacheRegion[currentTabIndex.value]?.tabIndex === currentTabIndex.value) {
				const answers = cacheRegion[currentTabIndex.value].answers;
				answers.pop(); // 删除最后一个数字
				cacheRegion[currentTabIndex.value].quIndex -= 1;
			}
		}
	}

	const switchIt = (e : any) => {
		switch (e) {
			case "1":
				return 'A';
			case "2":
				return 'B';
			case "3":
				return 'C';
			case "4":
				return 'D';
			case "5":
				return 'E';
			case "6":
				return 'F';
			case "7":
				return 'G';
			case "8":
				return 'H';
			case "9":
				return 'I';
			case "10":
				return 'J';
			case "11":
				return 'K';
			case "12":
				return 'L';
			case "12":
				return 'M';
			default:
				return '';
		}
	}

	const showPopup = ref(false)
	const showOutPop = ref(false)


	const backPress = (() => {
		showPopup.value = true;

	})



	const allQuestionList = ref([])
	const questionListPop = (() => {
		allQuestionList.value = question.value.flat(Infinity)
		isOpenQuestListPop.value = true

	})
	const closeQuestionListPop = (() => {
		isOpenQuestListPop.value = false
	})


	const toQuestionByItem = ((item, index) => {
		let questionIndex = index
		let flag = true
		let isJump = false
		question.value.map((items) => {
			if (items.length > index && flag) {
				flag = false;
			} else {
				questionIndex = questionIndex - items.length
			}

		})
		if (index < 1) {
			isJump = true
		} else if (item.optId != null || allQuestionList.value[index - 1].optId != null) {
			isJump = true
		} else {

		}

		if (isJump) {
			curr_index.value = questionIndex;
			questionItem.value = item;
			uni.showToast({
				icon: "none",
				title: `已跳转到第${index + 1}题`
			})
		} else {
			uni.showToast({
				icon: "none",
				title: `只能跳转到已做题和当前应做题`
			})
		}
	})


	// 提交答案 
	async function submit() {
		try {

			getReports({ taskId: props.taskId }).then((res) => {
				uni.navigateTo({
					url: `/pages/evaluation/report/report?id=${res.data.data.records[0].id}`
				})
			})
		} catch (error) {
			// 处理错误
			console.log('提交答案错误', error)
		}
	}

	const exit = (() => {
		showPopup.value = false
		isOut.value = true
		uni.navigateBack()
	})

	let selectValue = ref('');
	let progressPercent = ref(0)

	const flag = ref(false)
	const timer = ref(null)
	const handleEnd = () => {
		timer.value.resetTime()
	}
</script>

<template>
	<articleTable ref="timer"></articleTable>
	<Navigator :fixed="true" background-color="transparent" status-bar left-icon="back" left-text="返回" customLeft
		title="心理测评" @clickLeft="backPress" class="absolute"></Navigator>
	<u-modal :show="showPopup" showCancelButton width="550rpx" @confirm="exit" @cancel="showPopup = false"
		confirmColor='#49BEFF '>
		<view>
			<text v-if="taskObj.queCount-finishedNum>0" style="font-size: 0.8rem;">还有<text
					style="font-size: 0.8rem;color: coral;">{{" "+taskObj.queCount-finishedNum+" "}}</text>道题未做是否确定要退出测试</text>
			<text style="font-size: 0.8rem;">是否确定要退出测试</text>
		</view>
	</u-modal>
	<u-modal :show="showOutPop" showCancelButton width="550rpx" @confirm="submit" @cancel="showOutPop = false"
		confirmColor='#49BEFF '>
		<view>
			<text style="font-size: 0.8rem;">已完成评测，是否退出？</text>
		</view>

	</u-modal>
	<view @touchend="handleEnd" class="wh100p body" style="padding-top: 2%;box-sizing: border-box;overflow: hidden;">
		<view class="wh100p  absolute card-box " style="top: 0;width: 20%;z-index: 99;"
			:style="{ right: flag ? '0':'-40%' }">
			<view class="flex-between column-center w100p">
				<text class="font36 colorffffff">全部题目</text>
				<view style="padding: 0 10px;" @click.stop="flag = false">
					<u-icon name="close" color="white" size="36"></u-icon>
				</view>
			</view>
			<view class="w100p flex-around" style="height: 95%;margin-top: 5%;flex-wrap: wrap; overflow: scroll;">
				<view v-for="(item,index) in allQuestionList" @click="toQuestionByItem(item,index)" class="card-item"
					:style="(item.optId!=null)? 'background: linear-gradient(90deg, #49BEFF 0%, #3186FC 100%);color:white':'color:white'">
					<view class="flex" style="justify-content: center;align-items: center;">
						{{(index+1) }}
					</view>
				</view>
				<view v-for="(item,index) in 4" class="card-item" style="background:transparent">
				</view>
			</view>
		</view>
		<view class="wh100p relative" style="padding:2% 4%;box-sizing: border-box;">
			<view class="flex-column wh100p ">
				<text class="scale-title">{{scaleName}}</text>
				<view class="flex column-center"
					style="margin-top: 1.5%;height: 5%;padding-bottom: 1%;border-bottom: 1px solid rgba(255, 255, 255, 0.50);">
					<text class="font24" style="color: white;line-height: 24px;margin-right: 1%;width: 6%;">当前进度</text>
					<view style="width: 75%;">
						<view class="lineProgress">
							<view
								style="height: 100%;background: linear-gradient(90deg, #49BEFF 0%, #3186FC 100%);width:0%;transition: all 0.5s ease;"
								:style="`width:${currentProgress||0}%`">
							</view>
						</view>
					</view>
					<text class="font24 ml24" style="color: white;">{{currentProgress||0}} %</text>
					<view style="margin-left: 40px;">
						<button class="flex-center column-center" @click="flag = true"
							style="background-color: rgba(52, 139, 253, 0.20);color:white;font-size: 20px;padding: 12px 24px;border-radius: 12px;">
							<svg xmlns="http://www.w3.org/2000/svg" width="25" height="24" viewBox="0 0 25 24"
								fill="none">
								<path
									d="M9.26379 3H4.26379C3.71151 3 3.26379 3.44771 3.26379 4V9C3.26379 9.5523 3.71151 10 4.26379 10H9.26379C9.81609 10 10.2638 9.5523 10.2638 9V4C10.2638 3.44771 9.81609 3 9.26379 3Z"
									stroke="white" stroke-width="2" stroke-linejoin="round" />
								<path
									d="M9.26379 14H4.26379C3.71151 14 3.26379 14.4477 3.26379 15V20C3.26379 20.5523 3.71151 21 4.26379 21H9.26379C9.81609 21 10.2638 20.5523 10.2638 20V15C10.2638 14.4477 9.81609 14 9.26379 14Z"
									stroke="white" stroke-width="2" stroke-linejoin="round" />
								<path
									d="M20.2638 3H15.2638C14.7115 3 14.2638 3.44771 14.2638 4V9C14.2638 9.5523 14.7115 10 15.2638 10H20.2638C20.8161 10 21.2638 9.5523 21.2638 9V4C21.2638 3.44771 20.8161 3 20.2638 3Z"
									stroke="white" stroke-width="2" stroke-linejoin="round" />
								<path
									d="M20.2638 14H15.2638C14.7115 14 14.2638 14.4477 14.2638 15V20C14.2638 20.5523 14.7115 21 15.2638 21H20.2638C20.8161 21 21.2638 20.5523 21.2638 20V15C21.2638 14.4477 20.8161 14 20.2638 14Z"
									stroke="white" stroke-width="2" stroke-linejoin="round" />
							</svg>
							<text style="line-height: 24px;">全部题目</text></button>
					</view>
				</view>
				<view class="question-name mt20">
					<text class="font36 colorffffff "
						style="line-height: 48px;">{{curr_index+1}}.{{questionItem?.title}}</text>
				</view>
				<view class="question-section mt20">
					<view style="padding-left: 20rpx;padding-right: 20rpx;">
						<view class="options mt20" v-for="(an,index2) in questionItem?.options" :key="index2">
							<view class="op h100p" :data-val="an.value"
								@click="throttledHandleOptionClick( questionItem.id,an.id,questionItem.tabId,questionItem)"
								ref="dataVal">
								<view class="colorffffff  wh100p flex column-center"
									style="padding-left: 30rpx;font-size:32px;">
									<img
										:src="an.id != questionItem.optId?'@/../static/img/radio/unClickRadio.svg':'@/../static/img/radio/radio.svg'" />
									<text class="ml16"
										style="line-height: 32px;font-size: 32px;">{{switchIt(an.index)}}.{{an.title}}</text>
								</view>
							</view>
						</view>
					</view>
				</view>
				<view class="w100p flex-end"
					style=" height: 100rpx;padding-left: 30rpx;padding-right: 30rpx;margin-top:10%;margin-bottom: 40rpx;">
					<view style=" height: 250rpx;width: 10%;padding-right: 1%;">
						<button style="background-color: #55bbf9;color:white" v-show="curr_index>0"
							@click="back">上一题</button>
						<button style="background-color: #27ecbb;color:white ;margin-top: 10rpx;"
							v-show="curr_index===question[currentTabIndex]?.length-1 && currentTabIndex === question.length-1 && question[currentTabIndex][curr_index].optId !=null"
							@click="showOutPop =true">完成</button>
					</view>
				</view>
			</view>
		</view>

	</view>
</template>


<style lang="scss" scoped>
	.question {
		margin-top: 10%;
		margin-left: 10%;
		margin-bottom: 120rpx;
		width: 80%;
		font-weight: 600;
		font-size: 1.2rem;

	}

	.options {

		width: 100%;
		min-height: 80rpx;
		line-height: 80rpx;
		font-size: 0.9rem;
	}

	.op {
		width: 100%;
		display: flex;
		justify-content: space-between;
		margin-top: 20rpx;
		margin-bottom: 20rpx;
	}

	page {
		// background: linear-gradient(90deg, #0078BB 0%, #003E94 100%)
	}

	.title {
		font-size: 80rpx;

		color: rgba(255, 217, 181, 0.80);
		text-shadow: #ec9c01 1rpx 0 0, #ec9c01 0 1rpx 0, #ec9c01 -1rpx 0 0, #ec9c01 0 -1rpx 0;
		text-align: center;
	}

	.question-card {
		overflow-y: scroll;
		padding: 30rpx;
		border: 1px solid #dcdfe6;
	}

	.question-split {
		border-right: 1px solid #dcdfe6;

	}

	.scale-title {
		color: #FFF;
		font-family: PingFang SC;
		font-size: 48px;
		font-style: normal;
		font-weight: 600;
		line-height: normal;
	}

	.lineProgress {

		width: 100%;
		height: 18px;
		background: rgba(0, 0, 0, 0.20);
		border-radius: 10px;
		overflow: hidden;
		border: 0px;
		transition: all 0.5s ease;

	}

	.card-box {
		display: flex;
		box-sizing: border-box;
		padding: 2.5% 48px 32px 48px;
		flex-direction: column;
		align-items: flex-start;
		transition: all 0.5s ease;
		background: #0153A2;
	}

	.card-item {
		display: flex;
		width: 26%;
		height: 45px;
		// padding: 2px 8px;
		justify-content: center;
		align-items: center;
		margin-top: 2%;
		// margin-right: 1%;
		border-radius: 3px;
		background: rgba(49, 134, 252, 0.50);
	}

	.body {
		background: linear-gradient(90deg, #0078BB 0%, #003E94 100%);
	}
</style>